package com.sxz.sbs.util;

import android.content.Context;
import android.os.Environment;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 文件
 */

public class FileUtils {
    /**
     * 生成.json格式文件
     */
    public static boolean createJsonFile(Context context, String jsonString) {
        // 标记文件生成是否成功
        boolean flag = true;
        FileOutputStream outputStream;
        try {
            outputStream = context.openFileOutput("telbook", Context.MODE_PRIVATE);
            outputStream.write(jsonString.getBytes());
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        // 返回是否成功的标记
        return flag;
    }


    //读数据
    public static String readFile(Context context) throws IOException{
        StringBuilder sb = new StringBuilder();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(context.openFileInput("telbook")));
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

    public static String getJson(Context context) {
        StringBuilder stringBuilder = new StringBuilder();
        FileInputStream input = null;
        try {
            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String fileName = Environment.getExternalStorageState() + File.separator + "telbook.json";
            input = new FileInputStream(fileName);
            byte[] temp = new byte[1024];

            int len = 0;
            while ((len = input.read(temp)) > 0) {
                stringBuilder.append(new String(temp, 0, len));
            }
            //关闭输入流
            input.close();
         }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return stringBuilder.toString();
    }
}
